package com.qd.system.service.log;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cdqidi.api.service.ApManagerService;
import com.cdqidi.api.service.EnterpriseService;
import com.cdqidi.db.BaseService;
import com.qd.common.sys.domain.entity.log.SendLogDTO;
import com.qd.system.mapper.SendLogMapper;
import com.qd.system.model.SendLog;
import com.qd.system.service.dict.MbUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Collections;
import java.util.List;
import java.util.Optional;

import static java.util.stream.Collectors.toList;

/**
 * 发送日志
 *
 * @author sjk
 */
@RequiredArgsConstructor
@Service
@Slf4j
public class SendLogService extends BaseService<SendLogMapper, SendLog> {
    private final EnterpriseService enterpriseService;
    private final ApManagerService apManagerService;

    /**
     * 根据主键获取数据
     *
     * @param id 主键
     * @return 单条记录，转换成页面对象
     */
    @Transactional(readOnly = true)
    public SendLogDTO getByIdDto(String id) {
        return Optional.ofNullable(getById(id)).map(this::modelToDto).orElse(null);
    }

    /**
     * 分页数据
     *
     * @param page 分页对象
     * @param dto  查询参数
     * @return 分页信息
     */
    @Transactional(readOnly = true)
    public IPage<SendLogDTO> page(Page<SendLog> page, SendLogDTO dto) {
        final QueryWrapper<SendLog> queryWrapper = createQueryWrapper(dto, "t1.");
        queryWrapper.orderByDesc("t1.add_time");
        queryWrapper.orderByDesc("t1.send_state");
        queryWrapper.orderByAsc("t1.log_type");
        queryWrapper.orderByAsc("t1.app_id");
        final IPage<SendLogDTO> iPage = baseMapper.page(page, queryWrapper);
        queryWrapper.clear();
        Optional.ofNullable(iPage.getRecords()).ifPresent(l -> l.forEach(this::buildDisplay));
        return iPage;
    }

    /**
     * 数据库对象转页面对象
     *
     * @param model 数据库对象
     * @return 页面对象
     */
    public SendLogDTO modelToDto(SendLog model) {
        if (null == model) {
            return null;
        }
        final SendLogDTO dto = new SendLogDTO();
        dto.setId(model.getId());
        dto.setBid(model.getBid());
        dto.setChildBid(model.getChildBid());
        dto.setUrl(model.getUrl());
        dto.setReqParam(model.getReqParam());
        dto.setReqMethod(model.getReqMethod());
        dto.setResponseMsg(model.getResponseMsg());
        dto.setAddTime(model.getAddTime());
        dto.setErrMsg(model.getErrMsg());
        dto.setTimeConsumer(model.getTimeConsumer());
        dto.setLogType(model.getLogType());
        dto.setSendState(model.getSendState());
        dto.setAppId(model.getAppId());
        dto.setEId(model.getEId());
        buildDisplay(dto);
        return dto;
    }

    /**
     * 页面对象转数据库对象
     *
     * @param dto 页面对象
     * @return 数据库对象
     */
    public SendLog dtoToModel(SendLogDTO dto) {
        if (null == dto) {
            return null;
        }
        final SendLog model = new SendLog();
        model.setId(dto.getId());
        model.setBid(dto.getBid());
        model.setChildBid(dto.getChildBid());
        model.setUrl(dto.getUrl());
        model.setReqParam(dto.getReqParam());
        model.setReqMethod(dto.getReqMethod());
        model.setResponseMsg(dto.getResponseMsg());
        model.setAddTime(dto.getAddTime());
        model.setErrMsg(dto.getErrMsg());
        model.setTimeConsumer(dto.getTimeConsumer());
        model.setLogType(dto.getLogType());
        model.setSendState(dto.getSendState());
        model.setAppId(dto.getAppId());
        model.setEId(dto.getEId());
        return model;
    }
    /**
     * 码表转换
     *
     * @param dto 页面对象
     */
    public void buildDisplay(SendLogDTO dto) {
        dto.setEIdDisplay(enterpriseService.idToDisplay(dto.getEId()));
        dto.setAppIdDisplay(apManagerService.idToDisplay(dto.getAppId()));
        dto.setLogTypeDisplay(MbUtil.idToDisplay(dto.getLogType()));
        dto.setSendStateDisplay(MbUtil.idToDisplay(dto.getSendState()));
    }

    /**
     * 数据库对象转页面对象
     *
     * @param list 数据库对象
     * @return 页面对象
     */
    public List<SendLogDTO> modelToDtoList(List<SendLog> list) {
        return Optional.ofNullable(list).orElse(Collections.emptyList()).stream().map(this::modelToDto).collect(toList());
    }


    /**
     * 拼装查询参数，除了主键的其他字段会自动加入进来
     *
     * @param dto 查询参数，不为空的属性会被自动加入
     */
    public QueryWrapper<SendLog> createQueryWrapper(SendLogDTO dto) {
        return createQueryWrapper(dto, "");
    }

    /**
     * 拼装查询参数，除了主键的其他字段会自动加入进来
     *
     * @param dto        查询参数，不为空的属性会被自动加入
     * @param tableAlias 表别名
     */
    public QueryWrapper<SendLog> createQueryWrapper(SendLogDTO dto, String tableAlias) {
        final QueryWrapper<SendLog> queryWrapper = new QueryWrapper<>();
        if (null != dto) {
            if (StringUtils.hasLength(tableAlias) && tableAlias.charAt(tableAlias.length() - 1) != '.') {
                tableAlias += ".";
            }
            if (StringUtils.hasLength(dto.getBid())) {
                queryWrapper.eq(tableAlias + "bid", dto.getBid());
            }
            if (StringUtils.hasLength(dto.getChildBid())) {
                queryWrapper.eq(tableAlias + "child_bid", dto.getChildBid());
            }
            if (StringUtils.hasLength(dto.getAppId())) {
                queryWrapper.eq(tableAlias + "app_id", dto.getAppId());
            }
            if (StringUtils.hasLength(dto.getEId())) {
                queryWrapper.eq(tableAlias + "e_id", dto.getEId());
            }
            if (StringUtils.hasLength(dto.getLogType())) {
                queryWrapper.eq(tableAlias + "log_type", dto.getLogType());
            }
            if (StringUtils.hasLength(dto.getSendState())) {
                queryWrapper.eq(tableAlias + "send_state", dto.getSendState());
            }
        }
        return queryWrapper;
    }
}